package com.example.menhoo.toollibrary.common.helper;

import android.Manifest;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;

import com.example.menhoo.toollibrary.android.log.Log;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.utils.StringUtil;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yanglei on 15/10/22.
 */
public class PhoneUtil {

    /**
     * 打电话
     * @param context
     * @param phoneNumber
     */
    public static void callPhone(final Context context,final String phoneNumber)
    {
        if (context == null || StringUtil.isEmpty(phoneNumber)) {
            return;
        }
        //6.0权限处理
        Acp.getInstance(context).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.CALL_PHONE).build(), new AcpListener() {
            @Override public void onGranted() {
                Uri u = Uri.parse("tel:" + phoneNumber);
                Intent it = new Intent(Intent.ACTION_CALL, u);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
            }


            @Override public void onDenied(List<String> permissions) {

            }
        });
    }
    /**
     * 发短信
     * @param context
     * @param phoneNumber
     * @param content 短信内容
     */
    public static void callSMS(Context context,String phoneNumber,String content)
    {
        Uri uri = Uri.parse("smsto:"+phoneNumber);
        Intent it = new Intent(Intent.ACTION_SENDTO, uri);
        if(!Check.isEmpty(content) && !content.equalsIgnoreCase("null")){
            it.putExtra("sms_body", content);
        }

        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(it);
    }
    /**
     * 发邮件
     * @param context
     * @param emailAddress
     */
    public static void callEmail(Context context,String emailAddress)
    {
//        //建立Intent对象
//        Intent intent = new Intent();
//        //设置对象动作
//        intent.setAction(Intent.ACTION_SEND);
//        //设置对方邮件地址
//        intent.putExtra(Intent.EXTRA_EMAIL, new String[]
//                { emailAddress});
//        intent.setType("message/rfc822") ;
//        //设置标题内容
////	    intent.putExtra(Intent.EXTRA_SUBJECT, "test");
//        //设置邮件文本内容
////	     intent.putExtra(Intent.EXTRA_TEXT, "test mail");
////	     启动一个新的ACTIVITY,"Sending mail..."是在启动这个
////	      ACTIVITY的等待时间时所显示的文字
//        context.startActivity(intent);
        callEmail(context,emailAddress,null,null);
    }

    /**
     * 发送邮件
     * @param context
     * @param emailAddress email地址   可用';'号分割多个 email地址
     * @param subject 邮件主题
     * @param text 邮件正文
     */
    public static void callEmail(Context context,String emailAddress,String subject,String text)
    {
        //建立Intent对象
        Intent intent = new Intent();
        //设置对象动作
        intent.setAction(Intent.ACTION_SEND);
        //设置对方邮件地址
        intent.putExtra(Intent.EXTRA_EMAIL, emailAddress.split(";"));
        intent.setType("message/rfc822") ;
        //设置标题内容
        if(subject!=null && !subject.equalsIgnoreCase("null") && !Check.isEmpty(subject)){
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }

        //设置邮件文本内容
        if(text!=null && !text.equalsIgnoreCase("null") && !Check.isEmpty(text)){
            intent.putExtra(Intent.EXTRA_TEXT, text);
        }

//	     启动一个新的ACTIVITY,"Sending mail..."是在启动这个
//	      ACTIVITY的等待时间时所显示的文字
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    //[content://com.android.contacts/raw_contacts]
    private static final Uri RAW_CONTACTS_URI = ContactsContract.RawContacts.CONTENT_URI;
    //[content://com.android.contacts/data]
    private static final Uri DATA_URI = ContactsContract.Data.CONTENT_URI;

    private static final String ACCOUNT_TYPE = ContactsContract.RawContacts.ACCOUNT_TYPE;
    private static final String ACCOUNT_NAME = ContactsContract.RawContacts.ACCOUNT_NAME;

    private static final String RAW_CONTACT_ID = ContactsContract.Data.RAW_CONTACT_ID;
    private static final String MIMETYPE = ContactsContract.Data.MIMETYPE;

    private static final String NAME_ITEM_TYPE = ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
    private static final String DISPLAY_NAME = ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME;

    private static final String PHONE_ITEM_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
    private static final String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
    private static final String PHONE_TYPE = ContactsContract.CommonDataKinds.Phone.TYPE;
    private static final int PHONE_TYPE_HOME = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
    private static final int PHONE_TYPE_MOBILE = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

    private static final String EMAIL_ITEM_TYPE = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
    private static final String EMAIL_DATA = ContactsContract.CommonDataKinds.Email.DATA;
    private static final String EMAIL_TYPE = ContactsContract.CommonDataKinds.Email.TYPE;
    private static final int EMAIL_TYPE_HOME = ContactsContract.CommonDataKinds.Email.TYPE_HOME;
    private static final int EMAIL_TYPE_WORK = ContactsContract.CommonDataKinds.Email.TYPE_WORK;

    private static final String DEPT_ITEM_TYPE = ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE;
    private static final String GONG_SI_DATA = ContactsContract.CommonDataKinds.Organization.DATA;
    private static final String BU_MEN_DATA = ContactsContract.CommonDataKinds.Organization.JOB_DESCRIPTION;
    private static final String DEPT_TYPE = ContactsContract.CommonDataKinds.Organization.TYPE;
    private static final int DEPT_TYPE_WORK = ContactsContract.CommonDataKinds.Organization.TYPE_WORK;

    private static final String AUTHORITY = ContactsContract.AUTHORITY;

    /**
     * 添加联系人，使用事务
     * @param context
     * @param contactsInfo
     * @throws Exception
     */
    public static void addContact(Context context,ContactsInfo contactsInfo)throws Exception
    {
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

        ContentProviderOperation operation = ContentProviderOperation.newInsert(RAW_CONTACTS_URI)
                .withValue(ACCOUNT_TYPE, null)
                .withValue(ACCOUNT_NAME, null)
                .build();
        operations.add(operation);

        //添加联系人名称操作
        operation = ContentProviderOperation.newInsert(DATA_URI)
                .withValueBackReference(RAW_CONTACT_ID, 0)
                .withValue(MIMETYPE, NAME_ITEM_TYPE)
                .withValue(DISPLAY_NAME, contactsInfo.getName())
                .build();
        operations.add(operation);

        //		//添加家庭座机号码
        //		operation = ContentProviderOperation.newInsert(DATA_URI)
        //									.withValueBackReference(RAW_CONTACT_ID, 0)
        //									.withValue(MIMETYPE, PHONE_ITEM_TYPE)
        //									.withValue(PHONE_TYPE, PHONE_TYPE_HOME)
        //									.withValue(PHONE_NUMBER, "01034567890")
        //									.build();
        //		operations.add(operation);

        //添加移动手机号码
        operation = ContentProviderOperation.newInsert(DATA_URI)
                .withValueBackReference(RAW_CONTACT_ID, 0)
                .withValue(MIMETYPE, PHONE_ITEM_TYPE)
                .withValue(PHONE_TYPE, PHONE_TYPE_MOBILE)
                .withValue(PHONE_NUMBER, contactsInfo.getMobile())
                .build();
        operations.add(operation);

        //		//添加家庭邮箱
        //		operation = ContentProviderOperation.newInsert(DATA_URI)
        //									.withValueBackReference(RAW_CONTACT_ID, 0)
        //									.withValue(MIMETYPE, EMAIL_ITEM_TYPE)
        //									.withValue(EMAIL_TYPE, EMAIL_TYPE_HOME)
        //									.withValue(EMAIL_DATA, "scott@android.com")
        //									.build();
        //		operations.add(operation);

        //添加工作邮箱
        operation = ContentProviderOperation.newInsert(DATA_URI)
                .withValueBackReference(RAW_CONTACT_ID, 0)
                .withValue(MIMETYPE, EMAIL_ITEM_TYPE)
                .withValue(EMAIL_TYPE, EMAIL_TYPE_WORK)
                .withValue(EMAIL_DATA, contactsInfo.getEmail())
                .build();
        operations.add(operation);

        //添加部门
        operation = ContentProviderOperation.newInsert(DATA_URI)
                .withValueBackReference(RAW_CONTACT_ID, 0)
                .withValue(MIMETYPE, DEPT_ITEM_TYPE)
                .withValue(DEPT_TYPE, DEPT_TYPE_WORK)
                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, contactsInfo.getCompanyname())//公司
                        //									.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, "DEPARTMENT")
                        //									.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, "xx")
                        //									.withValue(ContactsContract.CommonDataKinds.Organization.LABEL, "LABEL")
                .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, contactsInfo.getJob())//职位
                        //									.withValue(ContactsContract.CommonDataKinds.Organization.JOB_DESCRIPTION, "JOB_DESCRIPTION")
                        //									.withValue(ContactsContract.CommonDataKinds.Organization.SYMBOL, "SYMBOL")
                .build();
        operations.add(operation);


        //添加图片
        Bitmap bm =contactsInfo.getLogo();//  BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_launcher); //context.getResources().getd;
        if (bm != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 0, baos);
            byte[] photo = baos.toByteArray();
            if (photo != null) {
                operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                        .withValue(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
                        .build());
            }
        }

        ContentResolver resolver = context.getContentResolver();
        //批量执行,返回执行结果集
        ContentProviderResult[] results = resolver.applyBatch(AUTHORITY, operations);
        for (ContentProviderResult result : results) {
            Log.d(result.uri.toString());
        }
    }

    public class ContactsInfo {

        String name;

        String homenumber;

        String mobile;

        String companyname;

        String job;

        String address;

        String notes;

        String email;

        String fax;

        Bitmap logo;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getHomenumber() {
            return homenumber;
        }

        public void setHomenumber(String homenumber) {
            this.homenumber = homenumber;
        }

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }

        public String getCompanyname() {
            return companyname;
        }

        public void setCompanyname(String companyname) {
            this.companyname = companyname;
        }

        public String getJob() {
            return job;
        }

        public void setJob(String job) {
            this.job = job;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getNotes() {
            return notes;
        }

        public void setNotes(String notes) {
            this.notes = notes;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getFax() {
            return fax;
        }

        public void setFax(String fax) {
            this.fax = fax;
        }

        public Bitmap getLogo() {
            return logo;
        }

        public void setLogo(Bitmap logo) {
            this.logo = logo;
        }



    }
}
